package com.by.datasource.tenant;

import com.baomidou.mybatisplus.annotation.TableName;
import com.by.toolkitspring.customizeannotation.AbstractByAnnotationContext;
import com.by.toolkitspring.customizeannotation.ByAnnotationProcessor;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class TProjectIdContext implements AbstractByAnnotationContext<TProjectId> {

    private static final Set<Class<?>> CLASSES = Sets.newHashSet();

    private static final Set<String> TABLE_NAMEES = Sets.newHashSet();

    @Override
    public void receiveContext(List<ByAnnotationProcessor.CustomizeAnnotationInfo> infos) {
        if (CollectionUtils.isEmpty(infos)) {
            return;
        }
        CLASSES.addAll(infos.stream()
                .map(ByAnnotationProcessor.CustomizeAnnotationInfo::getBeanClass)
                .collect(Collectors.toSet()));

        TABLE_NAMEES.addAll(infos.stream()
                .map(info -> {
                    TableName tableName = info.getBeanClass().getAnnotation(TableName.class);
                    return StringUtils.defaultIfBlank(tableName.value(), null);
                }).filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet()));
    }

    public boolean projectIdFlag(String tableName) {
        return TABLE_NAMEES.contains(tableName);
    }

}
